//
//  HomeSearchVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/26.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "HomeSearchVC.h"
#import "SearchTitleCell.h"
#import "SearchContentCell.h"
#import "WriteRequirementCollectionCell.h"
#import "HomeSearchHeadView.h"
#import "HomeModel.h"
#import "ServiceModel.h"
#import "SearchHeadView.h"
#import "HomeSearchServeTabVC.h"
#import "ServiceContentTabVC.h"
#import "HomeSearchDemandTabVC.h"
#import "DemandTheHallContentVC.h"
#import "SpecialRecommendationModel.h"
#import "ShopSubModel.h"
#import "UIView+TYAlertView.h"
#import "HotSearchModel.h"
#import "CellFrameModel.h"
#import "NowSearchCell.h"
#import "SearchShopTabVC.h"
#import "MyCollectShopContentVC.h"
#import "SubjectRecommendContentTabVC.h"
#import "SubjectRecommendContentTabVC.h"
@interface HomeSearchVC ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,SearchHeadViewDelegate,SearchTitleCellDelegate,WriteRequirementCollectionCellDelegate,HomeSearchHeadViewDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) HomeSearchHeadView *searchView;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) NSMutableArray *demandArray;
@property(nonatomic,strong) NSMutableArray *tempDir;
@property(nonatomic,strong) NSMutableArray *hotSerarchMuta;
@property(nonatomic,strong) NSMutableArray *serveMuta;
@property(nonatomic,strong) NSArray *date;
@property(nonatomic,strong) NSMutableArray *shopMuta;
@property(nonatomic,strong) NSMutableArray *specialArray;
@property(nonatomic,strong) NSMutableArray *banners;
@property(nonatomic,strong) HomeSearchServeTabVC *searchServiceVC;
@property(nonatomic,strong) HomeSearchDemandTabVC *searchDemandVC;
@property(nonatomic,strong) SearchShopTabVC *seachShopVC;
@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) UIScrollView *headScrollView;
@property(nonatomic,strong) SearchHeadView *headView;
@property(nonatomic,strong) UIImageView *headIV;
@property(nonatomic,assign) BOOL hiddenKey;
@property(nonatomic,assign) NSInteger nowSearch;
@property(nonatomic,assign) NSInteger pageNum;
@property(nonatomic,assign) NSInteger pageSize;
@end
@implementation HomeSearchVC
-(NSMutableArray *)tempDir
{
    if (!_tempDir) {
        //读取
        /**
         NSArray *temp = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
         NSString *fileNamed = [temp[0] stringByAppendingPathComponent:@"homeSearchPreference.plist"];
         */
        NSArray *pathFile = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *homeSearchPreference = [pathFile[0] stringByAppendingPathComponent:@"homeSearchPreference.plist"];
        XLog(@"homeSearchPreference:%@",homeSearchPreference);
        NSArray *temp = [NSArray arrayWithContentsOfFile:homeSearchPreference];
        XLog(@"temp.count:%ld",temp.count);
        if (temp.count) {
            _tempDir = [NSMutableArray arrayWithArray:temp];
        }else {
            _tempDir = [NSMutableArray array];
        }
        
    }
    return _tempDir;
    
}
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kVWidth, kVHeight-kNavAndStatusHight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        
    }
    return _tableView;
}
-(NSMutableArray *)demandArray
{
    if (!_demandArray) {
        _demandArray = [NSMutableArray array];
        
    }
    return _demandArray;
}
-(NSMutableArray *)hotSerarchMuta
{
    if (!_hotSerarchMuta) {
        _hotSerarchMuta = [NSMutableArray array];
        
    }
    return _hotSerarchMuta;
}
-(NSMutableArray *)serveMuta
{
    if (!_serveMuta) {
        _serveMuta = [NSMutableArray array];
    }
    return _serveMuta;
}
-(NSMutableArray *)shopMuta
{
    if (!_shopMuta) {
        _shopMuta = [NSMutableArray array];
    }
    return _shopMuta;
}
-(NSMutableArray *)specialArray
{
    if (!_specialArray) {
        _specialArray = [NSMutableArray array];
        
    }
    return _specialArray;
}
-(NSMutableArray *)banners
{
    if (!_banners) {
        _banners = [NSMutableArray array];
        
    }
    return _banners;
}
-(void)viewDidAppear:(BOOL)animated
{
    XLog(@"self:%@",self.navigationController.viewControllers);
    if (!self.hiddenKey) {
        [self.searchView.tf becomeFirstResponder];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setBackgroundImage:[ImageColorHelper createImageWithColor:[UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1]] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.searchView.tf resignFirstResponder];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = kWhite;
    self.manager = [AFHTTPSessionManager manager];
    //搜索栏
    self.searchView = [[HomeSearchHeadView alloc]initWithFrame:CGRectMake(0, 0, kVWidth*0.8,self.navigationController.navigationBar.frame.size.height-8)];
    self.searchView.delegate = self;
    
    self.navigationItem.titleView = self.searchView;
    
    [self.view addSubview:self.tableView];
    self.pageNum = 1;
    self.pageSize = 10;
    [self hotSearchData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hotSeachlist:) name:@"hotSeachlist" object:nil];
    
    NSString *homeDir = NSHomeDirectory();
    XLog(@"homeDir:%@",homeDir);
    NSArray *temp = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *fileNamed = [temp[0] stringByAppendingPathComponent:@"homeSearchPreference.plist"];
    __weak typeof (self)weakSelf = self;
    self.searchView.returnValueSearcBlock = ^(NSInteger selected, NSString * _Nonnull text) {
        weakSelf.text = text;
        weakSelf.nowSearch = 2;
        if (text.length >0) {
            if (![weakSelf.tempDir containsObject:weakSelf.text]) {
                [weakSelf.tempDir insertObject:text atIndex:0];
            }
            if (weakSelf.tempDir.count>= 4) {
                [weakSelf.tempDir removeObjectAtIndex:4];
            }
            [weakSelf.tempDir writeToFile:fileNamed atomically:YES];
            
        }
        [weakSelf.searchView.tf resignFirstResponder];
       [weakSelf reloadInternetData];
        XLog(@"self.tempDir:%@",weakSelf.tempDir);
    };
   
    
    
   
}
#pragma mark-代理:即时搜索
-(void)homeSearchHeadView:(HomeSearchHeadView *)homeSearchHeadView withTFChange:(UITextField *)tfChange;
{
    XLog(@"tfChange:%@",tfChange.text);
    self.tableView.hidden = NO;
    if (tfChange.text.length == 0) {
        self.nowSearch = 0;
        [self.tableView reloadData];
        [self.headView removeFromSuperview];
        [self.headScrollView removeFromSuperview];
        [self.scrollView removeFromSuperview];
//        if (self.nowSearch == 0||self.nowSearch == 1) {
//        }else {
//            self.tableView.hidden = YES;
//
//        }
    }else {

        self.nowSearch = 1;
        self.text = tfChange.text;
        [self reloadInternetData];
    }
}
-(void)hotSearchData
{
    [CustomeManager POSTWithURLIndex:48 parameters:nil success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)hotSeachlist:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *date = [dict objectForKey:@"date"];
    for (NSDictionary *dict in date) {
        HotSearchModel *model = [HotSearchModel mj_objectWithKeyValues:dict];
        [self.hotSerarchMuta addObject:model];
    }
//    NSIndexSet *set = [NSIndexSet indexSetWithIndex:1];
//    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView reloadData];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
#pragma mark-代理:搜索
-(void)reloadInternetData
{
    self.demandArray = nil;
    self.serveMuta = nil;
    self.shopMuta = nil;
    self.specialArray = nil;
    self.banners = nil;
    [self.headView removeFromSuperview];
    [self.headScrollView removeFromSuperview];
    [self.scrollView removeFromSuperview];
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    //使用GCD的信号量 dispatch_semaphore_t 创建同步请求
    dispatch_group_t group =dispatch_group_create();
    dispatch_queue_t globalQueue=dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    dispatch_group_async(group, globalQueue, ^{
        for (int i = 0; i<5; i++) {
            if (i == 0) {//需求
                self.urlString = [NSString stringWithFormat:@"%@/demand/selectDemandByTime",kUrl];
                self.dict = @{
                              @"pageNumber":[NumberSwitchString numberSwitchString:self.pageNum],
                              @"pageSize":[NumberSwitchString numberSwitchString:self.pageSize],
                              @"content":self.text,
                              @"uid":[UserDefaultsHelper readUid],
                              @"token":[UserDefaultsHelper readToken]
                              };
            }else  if (i == 1) {//服务
                self.urlString = [NSString stringWithFormat:@"%@/association/indexSearch",kUrl];
                self.dict = @{
                              @"page":[NumberSwitchString numberSwitchString:self.pageNum],
                              @"rows":[NumberSwitchString numberSwitchString:self.pageSize],
                              @"param":self.text,
                              @"order":@"0"
                              };
            }else  if (i == 2) {//店铺
                self.urlString = [NSString stringWithFormat:@"%@/shop/selectSerch",kUrl];
                self.dict = @{
                              @"content":self.text,
                              @"pageNumber":[NumberSwitchString numberSwitchString:self.pageNum],
                              @"pageSize":[NumberSwitchString numberSwitchString:self.pageSize],
                              @"uid":[UserDefaultsHelper readUid],
                              @"token":[UserDefaultsHelper readToken],
                              };
            }else if (i == 3) {//专题 服务
                self.urlString = [NSString stringWithFormat:@"%@/recommend/selectIndexRecommendAssociation",kUrl];
                self.dict = @{
                              @"serchRecommend":self.text,
                              @"uid":[UserDefaultsHelper readUid],
                              @"token":[UserDefaultsHelper readToken],
                              };
            }else {//专题 需求
                self.urlString = [NSString stringWithFormat:@"%@/recommend/selectIndexRecommendDemand",kUrl];
                self.dict = @{
                              @"serchRecommend":self.text,
                              @"uid":[UserDefaultsHelper readUid],
                              @"token":[UserDefaultsHelper readToken],
                              };
            }
            XLog(@"self.dict:%@",self.dict);
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSArray *temp = [responseObject objectForKey:@"date"];
                if (temp.count) {
                    
                    if (i == 0) {
                        for (NSDictionary *dict in temp) {
                            HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                            [self.demandArray addObject:model];
                        }
                        XLog(@"self.demandArray :%@",self.demandArray );
                    }else if (i == 1) {
                        for (NSDictionary *dict in temp) {
                            ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
                            [self.serveMuta addObject:model];
                        }
                        XLog(@"self.serveMuta:%@",self.serveMuta);
                    }else if (i == 2) {
//                        NSArray *date = [responseObject objectForKey:@"date"];
                        for (NSDictionary *dict in temp) {
                            ShopSubModel *model = [ShopSubModel mj_objectWithKeyValues:dict];
                            [self.shopMuta addObject:model];
                        }
                    
                    }else if (i == 3) {
                        XLog(@"reloadInternetData:%@",responseObject);
                        NSArray *date = [responseObject objectForKey:@"date"];
                        if (date.count) {
                            for (NSDictionary *dict in date) {
                                SpecialRecommendationModel *model =[SpecialRecommendationModel mj_objectWithKeyValues:dict];
                                [self.specialArray addObject:model];
                                [self.banners addObject:model.icon];
                            }
                        }
                    }else {
                        NSArray *date = [responseObject objectForKey:@"date"];
                        if (date.count) {
                            for (NSDictionary *dict in date) {
                                SpecialRecommendationModel *model =[SpecialRecommendationModel mj_objectWithKeyValues:dict];
                                [self.specialArray addObject:model];
                                [self.banners addObject:model.icon];
                            }
                        }
                    }
                }else {
//                    XLog(@"HomeresponseObject:%@",self.date);
                }
               
                dispatch_semaphore_signal(semaphore);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                XLog(@"error:%@",error);
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
        
    });
    self.hiddenKey = YES;
    dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
        XLog(@"%@---全部结束。。。",[NSThread currentThread]);
        XLog(@"self.demandArray:%@",self.demandArray);//1
        XLog(@"self.serveMuta:%@",self.serveMuta);//1
        XLog(@"self.shopMuta:%@",self.shopMuta);//上海
        XLog(@"self.specialArray:%@",self.specialArray);//a
//        XLog(@"nowSearch:%d",self.nowSearch);
        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.searchView.tf resignFirstResponder];
           
            __weak typeof (self)weakSelf = self;
            if (weakSelf.nowSearch ==2) {
                
                //头
                self.headView = [[SearchHeadView alloc]initWithFrame:CGRectMake(0, 0, kVWidth, 44)];
                self.headView.backgroundColor = kWhite;
                self.headView.delegate = self;
                [self.view addSubview:self.headView];
                if (self.specialArray.count) {
                    self.headScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame), kVWidth, 100)];
                    self.headScrollView.backgroundColor = kWhite;
                    self.headScrollView.showsHorizontalScrollIndicator = NO;
                    self.headScrollView.contentSize = CGSizeMake(self.specialArray.count*(200+18), 0);
                    [self.view addSubview:self.headScrollView];
                    self.headScrollView.frame =CGRectMake(0, CGRectGetMaxY(self.headView.frame), kVWidth, 100);
                    CGFloat margin = 18;
                    CGFloat w = 200;
                    CGFloat h = 90;
                    for (int i = 0; i < self.specialArray.count; i++) {
                        self.headIV = [[UIImageView alloc]initWithFrame:CGRectMake(margin*(i+1)+i*w, 5, w, h)];
                        self.headIV.userInteractionEnabled = YES;
                        [self.headScrollView addSubview:self.headIV];
                        [self.headIV sd_setImageWithURL:[NSURL URLWithString:self.banners[i]] placeholderImage:[UIImage imageNamed:@""]];
                        UIButton *btn = [[UIButton alloc]initWithFrame:self.headIV.bounds];
                        btn.tag = i;
                        [btn addTarget: self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
                        [self.headIV addSubview:btn];
                        
                    }
                }else {
                    self.headScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame), kVWidth, 0)];
                }
                self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headScrollView.frame), kVWidth, kVHeight-CGRectGetMaxY(weakSelf.headScrollView.frame))];
                self.scrollView.backgroundColor = [UIColor blueColor];
                self.scrollView.delegate = self;
                self.scrollView.contentSize = CGSizeMake(3*kUIScreen.size.width, 0);
                self.scrollView.pagingEnabled = YES;
                self.scrollView.showsHorizontalScrollIndicator = NO;
                self.scrollView.backgroundColor = kWhite;
                [self.view addSubview:self.scrollView];
                
                self.searchServiceVC = [[HomeSearchServeTabVC alloc]init];
                self.searchServiceVC.serveMuta = self.serveMuta;
                self.searchServiceVC.text = self.text;
                self.searchServiceVC.view.frame = CGRectMake(0, 0, kVWidth, self.scrollView.frame.size.height);
                [self.scrollView addSubview:self.searchServiceVC.view];
                self.searchServiceVC.returnValueBlock = ^(NSInteger row) {
                    ServiceContentTabVC *homeServiceVC = [[ServiceContentTabVC alloc]init];
                    ServiceModel *model = weakSelf.serveMuta[row-1];
                    homeServiceVC.model = model;
                    [weakSelf.navigationController pushViewController:homeServiceVC animated:YES];
                };
                
                self.searchDemandVC = [[HomeSearchDemandTabVC alloc]init];
                [self.scrollView addSubview:self.searchDemandVC.view];
                self.searchDemandVC.view.frame = CGRectMake(kVWidth, 0, kVWidth, self.scrollView.frame.size.height);
                self.searchDemandVC.demandArray = self.demandArray;
                self.searchDemandVC.text = self.text;
                self.searchDemandVC.returnValueBlock = ^(NSInteger row) {
                    DemandTheHallContentVC *vc = [[DemandTheHallContentVC alloc]init];
                    vc.homeModel  = weakSelf.demandArray[row-1];
                    XLog(@"需求概括:%@",vc.homeModel.represent);
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                };
                
                self.seachShopVC = [[SearchShopTabVC alloc]init];
                [self.scrollView addSubview:self.seachShopVC.view];
                self.seachShopVC.view.frame = CGRectMake(kVWidth*2, 0, kVWidth, self.scrollView.frame.size.height);
                self.seachShopVC.shopMuta = self.shopMuta;
//                self.seachShopVC.text = self.text;
                
                self.seachShopVC.returnValueBlock = ^(NSInteger row) {
                    MyCollectShopContentVC *vc = [[MyCollectShopContentVC alloc]init];
                    vc.model  = weakSelf.shopMuta[row];
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                };
                
            }
            XLog(@"headView:%@",NSStringFromCGRect(self.headView.frame));
            XLog(@"headScrollView:%@",NSStringFromCGRect(self.headScrollView.frame));
            [WSProgressHUD dismiss];
            if (!self.demandArray.count&&!self.serveMuta.count&&!self.shopMuta.count&&!self.specialArray.count) {
                self.tableView.emptyDataSetSource = self;
                self.tableView.emptyDataSetDelegate = self;
            }
            [self.searchView.tf resignFirstResponder];
            [self.tableView reloadData];
        });
    });
}
#pragma mark-点击专题推荐
-(void)clickBtn:(UIButton *)clickBtn
{
    SubjectRecommendContentTabVC *homeVC = [[SubjectRecommendContentTabVC alloc]init];
    homeVC.specialModel = self.specialArray[clickBtn.tag];
    if (homeVC.specialModel.type == 1) {
        homeVC.index = 0;
    }else {
        homeVC.index = 1;
    }
    [self.navigationController pushViewController:homeVC animated:YES];
}
#pragma mark-代理:点击--->服务,需求,店铺
-(void)searchHeadView:(SearchHeadView *)searchHeadView withBtn:(UIButton *)btn
{
    [self.scrollView setContentOffset:CGPointMake((btn.tag-1)*kVWidth, 0) animated:NO];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self.searchView.tf resignFirstResponder];
    NSInteger index = scrollView.contentOffset.x/kVWidth;
    MCButton *mcBtn = (MCButton *)[self.headView viewWithTag:index+1];
    [self.headView clickBtn:mcBtn];
}
- (NSInteger)numberOfSectionsInTableView:(UICollectionView *)tableView
{
    if (self.nowSearch == 0) {
        if (self.tempDir.count) {
            return 2;
        }else {
            return 1;
        }
    }else {
        return 4;
    }
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.nowSearch == 0) {
        if (section == 0) {
            return  self.tempDir.count?self.tempDir.count+1:2;
        }else {
            return 2;
        }
        
    }else {
        if (section == 0) {
            return self.specialArray.count;
        }else if (section == 1) {
            return self.serveMuta.count;
        }else  if (section == 2) {
            return self.demandArray.count;
        }else {
            return self.shopMuta.count;
        }
    }
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    XLog(@"self.tempDir.count:%ld",self.tempDir.count);
    XLog(@"self.tempDir:%@",self.tempDir);
    if (self.nowSearch == 0) {
            if (self.tempDir.count) {
                if (indexPath.section == 0) {
                    if (indexPath.row == 0) {
                        SearchTitleCell *cell = [SearchTitleCell cellNibWithTableView:tableView];
                        cell.indexPath = indexPath;
                        cell.delegate = self;
                        cell.deleBtn.hidden = NO;
                        cell.titleL.text = [NSBundle bundleLocalizedStringForKey:@"searchHistory"];
                        return cell;
                    }else {
                        SearchContentCell *cell = [SearchContentCell cellNibWithTableView:tableView];
                        if (self.tempDir.count) {
                            cell.titleL.text = self.tempDir[indexPath.row -1];
                        }
                        return cell;
                    }
                    
                }else {
                    if (indexPath.row == 0) {
                        SearchTitleCell *cell = [SearchTitleCell cellNibWithTableView:tableView];
                        cell.indexPath = indexPath;
                        cell.titleL.text = [NSBundle bundleLocalizedStringForKey:@"searchHotHistory"];
                        cell.deleBtn.hidden = YES;
                        return cell;
                    }else {
                        WriteRequirementCollectionCell *cell = [WriteRequirementCollectionCell cellWithTableView:tableView];
                        cell.delegate = self;
                        cell.titles = self.hotSerarchMuta;
                        return cell;
                    }
                }
            }else {
                if (indexPath.row == 0) {
                    SearchTitleCell *cell = [SearchTitleCell cellNibWithTableView:tableView];
                    cell.indexPath = indexPath;
                    cell.titleL.text = [NSBundle bundleLocalizedStringForKey:@"searchHotHistory"];
                    cell.deleBtn.hidden = YES;
                    return cell;
                }else {
                     WriteRequirementCollectionCell *cell = [WriteRequirementCollectionCell cellWithTableView:tableView];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    cell.delegate = self;
                    cell.titles = self.hotSerarchMuta;
                    return cell;
                }
            }
    }else {
        NowSearchCell *cell = [NowSearchCell cellNibWithTableView:tableView];
        XLog(@"self.shopMuta.count:%ld",self.shopMuta.count);
        XLog(@"self.serveMuta.count:%ld",self.serveMuta.count);
        XLog(@"self.demandArray.count:%ld",self.demandArray.count);
        cell.title = self.text;
        if (indexPath.section == 0) {
            if (self.specialArray.count) {
                SpecialRecommendationModel *specialModel = self.specialArray[indexPath.row];
                cell.specialModel = specialModel;
            }
        }else if (indexPath.section == 1) {
            if (self.serveMuta.count) {
                ServiceModel *serviceModel = self.serveMuta[indexPath.row];
                cell.serviceModel = serviceModel;
            }
        }else if (indexPath.section == 2) {
            if (self.demandArray.count) {
                HomeModel *model = self.demandArray[indexPath.row];
                cell.model = model;
            }
        }else {
            if (self.shopMuta.count) {
                ShopSubModel *subShopModel = self.shopMuta[indexPath.row];
                cell.subShopModel = subShopModel;
            }
        }
        
        
        
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 &&indexPath.row != 0) {
        TYAlertView *alertView = [TYAlertView alertViewWithTitle:[NSBundle bundleLocalizedStringForKey:@"deleSearchHistoryTitle"] message:@""];
        [alertView addAction:[TYAlertAction actionWithTitle:[NSBundle bundleLocalizedStringForKey:@"cencel"] style:TYAlertActionStyleCancel handler:^(TYAlertAction *action) {
        }]];
        [alertView addAction:[TYAlertAction actionWithTitle:[NSBundle bundleLocalizedStringForKey:@"ok"] style:TYAlertActionStyleDestructive handler:^(TYAlertAction *action) {
            [self.tempDir removeObjectAtIndex:indexPath.row-1];
            NSArray *temp = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *fileNamed = [temp[0] stringByAppendingPathComponent:@"homeSearchPreference.plist"];
            [self.tempDir writeToFile:fileNamed atomically:YES];
            [self.tableView setEditing:NO animated:YES];
            [self.tableView reloadData];
        }]];
        [alertView showInWindowWithOriginY:200 backgoundTapDismissEnable:YES];
    }
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 &&indexPath.row !=0) {
        return UITableViewCellEditingStyleDelete;
    }else {
        return UITableViewCellEditingStyleNone;
    }
}

#pragma mark-代理:热门搜索
- (void)writeRequirementCollectionCell:(WriteRequirementCollectionCell *)writeRequirementCollectionCell withSelected:(BOOL)selected withIndexPath:(NSIndexPath *)indexPath withTag:(NSInteger)tag withBtn:(UIButton *)btn
{
    self.text = [btn currentTitle];
    self.nowSearch = 2;
    self.demandArray = nil;
    self.serveMuta = nil;
    self.shopMuta = nil;
    self.searchView.tf.text = self.text;
    [self reloadInternetData];
}
#pragma mark-代理:删除历史搜索
- (void)searchTitleCell:(SearchTitleCell *)searchTitleCell withDeleBtn:(UIButton *)deleBtn
{
    [self.searchView.tf resignFirstResponder];
    [self.tableView setEditing:deleBtn.selected animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 44;
    } else {
        return 44;
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.nowSearch != 1) {
        if (indexPath.section == 0 &&indexPath.row !=0) {
            self.nowSearch = 2;
            self.text = self.tempDir[indexPath.row -1];
            self.searchView.tf.text = self.text;
            [self reloadInternetData];
        }
        
    }else {

        XLog(@"self.text:%@",self.text);
        if (self.text.length >0) {
            if (![self.tempDir containsObject:self.text]) {
                [self.tempDir insertObject:self.text atIndex:0];
            }
            if (self.tempDir.count>= 4) {
                [self.tempDir removeObjectAtIndex:4];
            }
            NSArray *temp = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *fileNamed = [temp[0] stringByAppendingPathComponent:@"homeSearchPreference.plist"];
            [self.tempDir writeToFile:fileNamed atomically:YES];
            
        }
        if (indexPath.section == 0) {
            if (self.specialArray.count) {
                SubjectRecommendContentTabVC *vc = [[SubjectRecommendContentTabVC alloc]init];
                vc.specialModel  = self.specialArray[indexPath.row];
                if (vc.specialModel.type == 1) {
                    vc.index = 0;
                }else {
                    vc.index = 1;
                }
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else if (indexPath.section == 1) {
            if (self.serveMuta.count) {
                ServiceContentTabVC *vc = [[ServiceContentTabVC alloc]init];
                vc.model  = self.serveMuta[indexPath.row];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else if (indexPath.section == 2) {
            if (self.demandArray.count) {
                DemandTheHallContentVC *vc = [[DemandTheHallContentVC alloc]init];
                vc.homeModel  = self.demandArray[indexPath.row];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else {
            if (self.shopMuta.count) {
                MyCollectShopContentVC *vc = [[MyCollectShopContentVC alloc]init];
                vc.model  = self.shopMuta[indexPath.row];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
//    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
}

@end
